<?php

namespace Home\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Home\Model\Lienhe;
use Home\Form\LienheForm;
use Zend\Db\Sql\Select;
use Zend\Paginator\Paginator;
use Zend\Paginator\Adapter\Iterator as paginatorIterator;
use Zend\Session\Container;
use Zend\Mail;
use Zend\Mime\Message as MimeMessage;
use Zend\Mime\Part as MimePart;
use Zend\Mail\Transport\Smtp as SmtpTransport;
use Zend\Mail\Transport\SmtpOptions;

class LienheController extends AbstractActionController {

    
	public $menuTable;
	public $tintucTable;
	public $onlineTable;
	public $lienketTable;
	public $counterTable;
	public $visitTable;
	public $thongtinTable;

	public function generateAction()
    {
        $response = $this->getResponse();
        $response->getHeaders()->addHeaderLine('Content-Type', "image/png");
 
        $id = $this->params('id', false);
 
        if ($id) {
 
            $image = './data/captcha/' . $id;
 
            if (file_exists($image) !== false) {
                $imagegetcontent = @file_get_contents($image);
 
                $response->setStatusCode(200);
                $response->setContent($imagegetcontent);
 
                if (file_exists($image) == true) {
                    unlink($image);
                }
            }
 
        }
 
        return $response;
    }
	public function counter(){
		$sid = session_id();
		$CurrentTime = time();
		$TimeOut = $CurrentTime - 300;
		$this->getOnlineTable()->check_exists($sid,$CurrentTime,$TimeOut);
		$select = new Select();
		$online = $this->getOnlineTable()->fetchAll()->count();
		$this->getEvent()->getViewModel()->online = $online;
		////
		$today = date('d');
		$thang = date('m');
		$nam = date('Y');
		$ip = $this->getRequest()->getServer('REMOTE_ADDR');
		if($this->getVisitTable()->check_date($today,$thang,$nam))
		{
			if($this->getVisitTable()->check_ip($ip,$today,$thang,$nam))
			{
				if($sid!=$this->getVisitTable()->check_ip($ip,$today,$thang,$nam)->session)
				{
					$this->getVisitTable()->updateVisit($ip,$sid,$today,$thang,$nam);
					$this->getCounterTable()->updateLuotxem($today,$thang,$nam);
				}
			}
			else
			{
				$this->getVisitTable()->insertVisit($ip,$sid,$today,$thang,$nam);
				$this->getCounterTable()->updateLuongtruycap($today,$thang,$nam);
			}
		}
		else
		{
			$this->getVisitTable()->deleteVisit();
			$this->getVisitTable()->insertVisit($ip,$sid,$today,$thang,$nam);
			$this->getCounterTable()->insertCounter($today,$thang,$nam);
		}
		//$this->getCounterTable()->check_exists($today,$thang,$nam);
		
		$select = new Select();
		$tongtruycap = $this->getCounterTable()->sumCounter();
		
		$this->getEvent()->getViewModel()->tongtruycap = $tongtruycap->luongtruycap;
		/////// \Zend\Debug\Debug::dump($tongtruycap->luongtruycap);
		
		$select = new Select();
		$thongtin = $this->getThongtinTable()->fetchAll();
		
		$this->getEvent()->getViewModel()->banner = $thongtin->banner;
		$this->getEvent()->getViewModel()->footer = $thongtin->footer;
		$this->getEvent()->getViewModel()->yahoo = $thongtin->yahoo;
		$this->getEvent()->getViewModel()->skype = $thongtin->skype;
	}
    public function indexAction() {

		$module = "home";
		$controller = $this->params('controller');
		$action = $this->params('action');
		
		$sessionModule = new Container('module');
		$sessionController = new Container('controller');
		$sessionAction = new Container('action');
		$sessionModule->lastModule = $module;
		$sessionController->lastController = $controller;
		$sessionAction->lastAction = $action;
		
		$select = new Select();
		
		//// domain
		$domain = "/truonghoc";
		$this->getEvent()->getViewModel()->domain = $domain;
		///////
		$this->getEvent()->getViewModel()->chuyenmuc = "lienhe";

        $danhmuc = $this->getMenuTable()->fetchAllDanhmuc();
        $this->getEvent()->getViewModel()->danhmuc = $danhmuc;

		$canbiet = $this->getMenuTable()->fetchAllCanbiet();
        $this->getEvent()->getViewModel()->canbiet = $canbiet;
		
		$menuchinh = $this->getMenuTable()->fetchAllMenuchinh();
        $this->getEvent()->getViewModel()->menuchinh = $menuchinh;
		$this->getEvent()->getViewModel()->menuchinh1 = $menuchinh;
		
		$select = new Select();
		$noibat = $this->getTintucTable()->fetchAll($select->where(array('tinnoibat' => 'Nổi bật','trangthai' => 'Hiển thị'))->order('id desc')->limit(5));
		$this->getEvent()->getViewModel()->noibat = $noibat;
		
		/////
		$select = new Select();
		$moinhat = $this->getTintucTable()->fetchAll($select->where(array('trangthai' => 'Hiển thị'))->order('id desc')->limit(5));
		$this->getEvent()->getViewModel()->moinhat = $moinhat;
		
		/////
		/////
		$select = new Select();
		$quantam = $this->getTintucTable()->fetchAll($select->where(array('trangthai' => 'Hiển thị'))->order('soluotxem desc')->limit(5));
		$this->getEvent()->getViewModel()->quantam = $quantam;
		
		/////
		/////
		$select = new Select();
		$lienketwebsite = $this->getLienketTable()->fetchAll();
		$this->getEvent()->getViewModel()->lienketwebsite = $lienketwebsite;
		////
		$this->counter();
		
		$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $form = new LienheForm($dbAdapter);
        $form->get('submit')->setAttribute('value', 'Gửi');
		
		
		$select = new Select();
		$email = $this->getThongtinTable()->getThongtin(1)->email;
		
       	
        $request = $this->getRequest();
        if ($request->isPost()) {
			$form->setData($request->getPost());
 
            if ($form->isValid()) {
				$htmlBody = $request->getPost('hoten'); 
				$textBody = $request->getPost('noidung'); 
				$subject = $request->getPost('tieude'); 
				$from = $request->getPost('email'); 
				$to = $email;
				
				$htmlPart = new MimePart($htmlBody);
				$htmlPart->type = "text/html";
			
				$textPart = new MimePart($textBody);
				$textPart->type = "text/plain";
			
				$body = new MimeMessage();
				$body->setParts(array($textPart, $htmlPart));
			
				$message = new Mail\Message();
				$message->setFrom($from);
				$message->addTo($to);
				$message->setSubject($subject);
			
				$message->setEncoding("UTF-8");
				$message->setBody($body);
				$message->getHeaders()->get('content-type')->setType('multipart/alternative');
			
				// Setup SMTP transport using LOGIN authentication
				$transport = new SmtpTransport();
				$options   = new SmtpOptions(array(
					'name'              => 'gmail.com',
					'host'              => 'smtp.gmail.com',
					'port'              => 465, // Notice port change for TLS is 587
					'connection_class'  => 'smtp',
					'connection_config' => array(
						'username' => 'mail.khachhang.info@gmail.com',
						'password' => '19008198',
						'ssl'      => 'tls'
					),
				));
				$transport->setOptions($options);
				$transport->send($message);
				//xoa file
				$this->rmdir_recurse('./data/captcha');
				return new ViewModel(array(
					'error' => 'Yêu cầu của bạn đã được gửi đi',
					
                ));
			}
		}
		return array('form' => $form);
    }

    

    
	public function getMenuTable() {
        if (!$this->menuTable) {
            $sm = $this->getServiceLocator();
            $this->menuTable = $sm->get('Home\Model\MenuTable');
        }
        return $this->menuTable;
    }
	public function getTintucTable() {
        if (!$this->tintucTable) {
            $sm = $this->getServiceLocator();
            $this->tintucTable = $sm->get('Home\Model\TintucTable');
        }
        return $this->tintucTable;
    }
	public function getOnlineTable() {
        if (!$this->onlineTable) {
            $sm = $this->getServiceLocator();
            $this->onlineTable = $sm->get('Home\Model\OnlineTable');
        }
        return $this->onlineTable;
    }
	public function getLienketTable() {
        if (!$this->lienketTable) {
            $sm = $this->getServiceLocator();
            $this->lienketTable = $sm->get('Home\Model\LienketTable');
        }
        return $this->lienketTable;
    }
	public function getCounterTable() {
        if (!$this->counterTable) {
            $sm = $this->getServiceLocator();
            $this->counterTable = $sm->get('Home\Model\CounterTable');
        }
        return $this->counterTable;
    }
	public function getVisitTable() {
        if (!$this->visitTable) {
            $sm = $this->getServiceLocator();
            $this->visitTable = $sm->get('Home\Model\VisitTable');
        }
        return $this->visitTable;
    }
	public function getThongtinTable() {
        if (!$this->thongtinTable) {
            $sm = $this->getServiceLocator();
            $this->thongtinTable = $sm->get('Home\Model\ThongtinTable');
        }
        return $this->thongtinTable;
    }
	function rmdir_recurse($path) {
		$path = rtrim($path, '/').'/';
		$handle = opendir($path);
		while(false !== ($file = readdir($handle))) {
			if($file != '.' and $file != '..' ) {
				$fullpath = $path.$file;
				if(is_dir($fullpath)) rmdir_recurse($fullpath); else unlink($fullpath);
			}
		}
		closedir($handle);
		
	}

}
